/*
 * Copyright (c) 2025 Li Auto Inc. and its affiliates
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <edds/rtps/security/common/AuthToken.h>
#include <security/authentication/PKIDH.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>

namespace evbs {
namespace ertps {
namespace rtps {

namespace security {

std::pair<uint32_t, uint32_t> AuthToken::compute_authtoken(const std::vector<uint8_t>& key, std::vector<uint8_t>& data, uint32_t block_id) {
    uint32_t token1 = 0;
    uint32_t token2 = 0;
    unsigned char result[32] = {0};
    unsigned int result_len = 0;

    if (block_id > 0) {
        data.insert(data.end(), reinterpret_cast<uint8_t*>(&block_id),
                    reinterpret_cast<uint8_t*>(&block_id) + sizeof(block_id));
    }
    HMAC(EVP_sha256(), key.data(), key.size(), data.data(), data.size(), result, &result_len);

    (void)std::memcpy(&token1, result, sizeof(token1));
    (void)std::memcpy(&token2, result + sizeof(token1), sizeof(token2));

    return {token1, token2};
}

std::pair<uint32_t, uint32_t> AuthToken::compute_authtoken(std::vector<uint8_t>& data, uint32_t block_id) {
    uint32_t token1 = 0;
    uint32_t token2 = 0;
    std::vector<uint8_t> result(32, 0);
    SecurityException exception;

    if (block_id > 0) {
        data.insert(data.end(), block_id, sizeof(block_id));
    }

    if (PKIDH::mvbs_hmac_sha256(data.data(), data.size(), result, exception)) {
        (void)std::memcpy(&token1, result.data(), sizeof(token1));
        (void)std::memcpy(&token2, result.data() + sizeof(token1), sizeof(token2));
    }

    return {token1, token2};
}

void AuthToken::init() {
    first_token_ = 0;
    current_token_ = first_token_;
    session_block_edge = max_blocks_per_session;
}

void AuthToken::reset() {
    init();
}

}  // namespace security
}  // namespace rtps
}  // namespace ertps
}  // namespace evbs
